import {platformMap}  from '@/common/models.js'
import qs from '@/utils/qs.js'

const loginMixin = {
  data () {
    return {
      vid: 0,
      mid: 0,
    }
  },
  onLoad (e) {
    const that = this
    if (e.vid) {
      that.vid = ~~e.vid
      // uni.setStorageSync('loginByVid', e.vid)
    }
    if (e.mid) {
      that.mid = ~~e.mid
      // uni.setStorageSync('loginByMid', e.mid)
    }
    
    console.log(that)
  },
  mounted() {
    this.googleInit()
  },
  methods: {
    googleInit(){
      console.log('initialize google')
      let redirectURI = this.configs.webUrl + '/auth/google'
      google.accounts.id.initialize({
        client_id: this.configs.googleClientId,
        callback: this.googleLoginHandle,
        login_uri: redirectURI,
        context: "signin",
        ux_mode: "popup",
        auto_prompt: false
      })
      const parent = document.getElementById('google-btn');
      google.accounts.id.renderButton(parent, {
        type: "standard",
        theme: "outline",
        text: "signin_with",
        size: "large",
        width: Math.trunc(this.windowWidth * 0.9),
        locale: "en-US",
        logo_alignment: "left",
        shape: 'pill'
      });
    },
    googleLoginHandle(resopnse) {
      this.login(resopnse.credential, 'google')
    },
    // facebook登入
    bindLoginByFB () {
      const that = this;
      this.GAHandle('c_login', 2, {
        'event_label': 'login',
        vid: that.vid,
        mid: that.mid
      })
      if (that.isFBLoginIn) {
        FB.login(function(response){
          if (response.status === 'connected') {
            that.login(response.authResponse.accessToken, 'facebook')
            // Logged into your webpage and Facebook.
            return false;
          } 
        });
      }
      const facebookPath = 'https://www.facebook.com/v18.0/dialog/oauth';
      let locationUrl = this.configs.webUrl + '/auth/facebook';
      // locationUrl = 'https://localhost:9999/auth/facebook';
      let facebookState = 'fblogin2023'
      if (this.vid) {
        facebookState = `vid=${this.vid}&mid=${this.mid}`
      }
      const auth_params = {
        client_id: this.configs.fbClientId,
        state: facebookState,
        redirect_uri: locationUrl
      }
      const paramsString = qs.stringify(auth_params);
      window.location.href = `${facebookPath}?${paramsString}`;
    },
    bindLoginByGoogle () {
      const that = this;
      // Google's OAuth 2.0 endpoint for requesting an access token
      var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
      
      // Create element to open OAuth 2.0 endpoint in new window.
      var form = document.createElement('form');
      form.setAttribute('method', 'GET'); // Send as a GET request.
      form.setAttribute('action', oauth2Endpoint);
      
      // Parameters to pass to OAuth 2.0 endpoint.
      let redirectURI = that.configs.webUrl + '/auth/google'
      // redirectURI = 'https://localhost:9999/auth/google'
      let stateString = 'loginpage'
      if (that.loginRedirectUri) {
        stateString = that.loginRedirectUri
      }
      var params = {'client_id': that.configs.googleClientId,
                    'redirect_uri': redirectURI,
                    'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
                    'state': stateString,
                    'include_granted_scopes': 'true',
                    'response_type': 'token'};
      
          // Add form parameters as hidden input values.
          for (var p in params) {
            var input = document.createElement('input');
            input.setAttribute('type', 'hidden');
            input.setAttribute('name', p);
            input.setAttribute('value', params[p]);
            form.appendChild(input);
          }
      
          // Add form to page and submit it to open the OAuth 2.0 endpoint.
          document.body.appendChild(form);
          form.submit();
    },
    bindLoginByTikTok () {
      const that = this;
      // Google's OAuth 2.0 endpoint for requesting an access token
      var oauth2Endpoint = 'https://www.tiktok.com/v2/auth/authorize/';
      
      // Create element to open OAuth 2.0 endpoint in new window.
      var form = document.createElement('form');
      form.setAttribute('method', 'GET'); // Send as a GET request.
      form.setAttribute('action', oauth2Endpoint);
      
      // Parameters to pass to OAuth 2.0 endpoint.
      let redirectURI = that.configs.webUrl + '/auth/tiktok'
      // redirectURI = 'https://localhost:9999/auth/tiktok'
      
      let stateString = 'loginpage'
      if (that.loginRedirectUri) {
        uni.setStorageSync('loginRedirectUri', that.loginRedirectUri)
        // stateString = that.loginRedirectUri
      }
      
      
      var params = {'client_key': that.configs.tikTokClientKey,
                    'redirect_uri': redirectURI,
                    'scope': 'user.info.basic',
                    'state': redirectURI,
                    // 'state': stateString,
                    'response_type': 'code'};
      
          // Add form parameters as hidden input values.
          for (var p in params) {
            var input = document.createElement('input');
            input.setAttribute('type', 'hidden');
            input.setAttribute('name', p);
            input.setAttribute('value', params[p]);
            form.appendChild(input);
          }
      
          // Add form to page and submit it to open the OAuth 2.0 endpoint.
          document.body.appendChild(form);
          form.submit();
    },
    login (responseAccessTokenOrCode, platfrom, isByCode) {
      const that = this
      uni.showLoading()
      let requestData = {
        vid: that.vid,
        mid: that.mid
      }
      isByCode ? requestData.code = responseAccessTokenOrCode : requestData.token = responseAccessTokenOrCode
        
      if (uni.getStorageSync('userFrom')) {
        requestData.source = uni.getStorageSync('userFrom')
      }
      if (uni.getStorageSync('guestId')) {
        requestData['guest_id'] = uni.getStorageSync('guestId')
      }
      uni.request({
        url: this.configs.apiUrl + '/api/user/' + platfrom,
        data: requestData,
        success(res) {
          that.handleLoginSuccess(res, platfrom);
        },
        complete() {
          uni.hideLoading()
        }
      })
      that.GAHandle('c_login', 3, {
        'event_label': 'login',
        vid: that.vid,
        mid: that.mid
      })
    },
    handleLoginSuccess (res, platfrom) {
      if(res.data.code === 1){
        uni.showToast({ title: this.$t('login.success'), icon:"success" });
        var avatar='';
        
        if(res.data.data.userinfo.avatar){
      		var str = res.data.data.userinfo.avatar;
      		if(str.indexOf("data:image") == -1){
      			if(str.indexOf("http") != -1){
      				avatar=res.data.data.userinfo.avatar;
      			}else{
      				avatar=this.configs.imgUrl+res.data.data.userinfo.avatar;
      			}
      		}
      	}
        uni.setStorage({
          key: 'avatar',  
          data: avatar
        })
        uni.setStorage({
          key: 'userinfo',  
          data: res.data.data.userinfo
        })
        uni.setStorage({
          key: 'userLoginType',
          data: res.data.data['login_type']
        })
        uni.setStorage({
          key: 'config',  
          data: res.data.data.config
        })
        
        this.GAHandle('login', platfrom == 'facebook' ? 2 : 0, {
          'code': platfrom,
          mid: this.mid,
          vid: this.vid
        })
        
        setTimeout(()=>{
          const loginRedirectUri = uni.getStorageSync('loginRedirectUri') || ''
          uni.removeStorageSync('loginRedirectUri')
          if (loginRedirectUri != '') {
            uni.reLaunch({
              url: decodeURIComponent(loginRedirectUri)
            })
          } else {
            const pages = getCurrentPages()
            // console.log({pages}, pages.length)
            if (pages.length == 1) {
              uni.reLaunch({
                url: '/pages/client/index'
              })
            } else {
              uni.navigateBack()
            }
          }
        }, 1500)
      } else {
        uni.showToast({ title: res.data.msg || this.$t('login.failed'), icon:"none" });
      }
    },
  }
}

export default loginMixin;
